package online.struts.filter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import online.filter.FilterUtil;
import online.filter.RouteRequestFilter;
import online.struts.mapping.RequestMapping;

import org.apache.struts.Globals;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ModuleConfig;

/**
 * ルート制御フィルタ
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class RoutingFilter extends RouteRequestFilter {

	/**
	 * @see online.filter.RouteRequestFilter
	 * #findTargetPath(javax.servlet.ServletContext, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	protected int findTargetPath(final ServletContext context, final HttpServletRequest request) {
		ModuleConfig mc = ModuleConfig.class.cast(context.getAttribute(Globals.MODULE_KEY));
		if (mc != null) {
			String path = FilterUtil.toPlainURI(request.getRequestURI());
			for (int s = path.lastIndexOf('/'), e = path.length(); 0 <= s;
							e = s, s = path.lastIndexOf('/', path.offsetByCodePoints(e, -1))) {
				String val = path.substring(s, e);
				if (val.endsWith(".do") || val.endsWith(".jsp") || val.endsWith(".jspx")
								|| val.endsWith(".css") || val.endsWith(".js")) {
					break;
				}
				ActionConfig ac = mc.findActionConfig(val);
				if (ac != null) {
					if (!FilterUtil.isGetMethod(request.getMethod())) {
						break;
					} else if (RequestMapping.class.isInstance(ac)) {
						RequestMapping rm = RequestMapping.class.cast(ac);
						if (rm.getKeepId() != null) {
							break;
						}
					}
					return s;
				} else if (s <= 0) {
					break;
				}
			}
		}
		return -1;
	}

	/**
	 * @see online.filter.RouteRequestFilter#getTargetPath(java.lang.String)
	 */
	@Override
	protected String getTargetPath(final String target) {
		return target + ".do";
	}
}
